<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图层切换控件</title>
    <link rel="stylesheet" href="../v6.4.3/css/ol.css">
  </head>

  <body>
    <div id="controls">
      <input type="radio" id="osm" name="mapType" checked />OpenStreetMap
      <input type="radio" id="bingmap" name="mapType" />Bing Map
      <input type="radio" id="stamen" name="mapType" />Stamen Map
    </div>
    <!-- 核心地图容器 -->
    <div id="map" style="height: 500px;"></div>

    <script src="../v6.4.3/build/ol.js"></script>
    <script>
      const map = new ol.Map({
        target: 'map',
        layers: [
          // OpenStreetMap 图层
          new ol.layer.Tile({
            source: new ol.source.OSM()
          }),
          // Bing Map图层
          new ol.layer.Tile({
            source: new ol.source.BingMaps({
              key: 'AgAUM7MqI1kfMW7nPRIljLGGKH6tDR-Fng_oVSUCcZXXs1p6oxnMqdkl9oV6eIOL',//'到BingMap官网申请key',
              imagerySet: 'Aerial'
            }),
            visible: false
          }),
          //
          new ol.layer.Tile({
            source: new ol.source.Stamen({
              layer: 'watercolor'
            }),
            visible: false
          })
        ],
        view: new ol.View({
          projection: 'EPSG:3857',
          center: [0, 0],
          zoom: 0
        }),
        // 新增代码，加上各种控件（Zoom控件是默认带上的）
        controls: ol.control.defaults().extend([
          new ol.control.ZoomSlider()
        ])
      })
      
      //切换图层事件
      //主要通过 layer.Tile类 的 setVisible 方法设置图层显示与隐藏
      const controls = document.getElementById('controls')
      controls.addEventListener('click', event => {
        console.log(event)
        if(event.target.checked) {
          map.getLayers().item(0).setVisible(false)
          map.getLayers().item(1).setVisible(false)
          map.getLayers().item(2).setVisible(false)
          switch(event.target.id) {
            case 'osm':
              map.getLayers().item(0).setVisible(true)
              break
            case 'bingmap':
              map.getLayers().item(1).setVisible(true)
              break
            case 'stamen':
              map.getLayers().item(2).setVisible(true)
              break
          }
        }
      })
    </script>
  </body>
</html>